﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using myMvcBlog.Infrastructure;

namespace myMvcBlog.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ActionResult OpenIDLogin(string openIdUrl, string postUrl)
        {
            OpenIdRelyingParty Openid = new OpenIdRelyingParty();

            var response = Openid.GetResponse();
            if (response == null)
            {
                // User submitting Identifier
                Identifier id;
                if (Identifier.TryParse(openIdUrl, out id))
                {
                    try
                    {
                        var request = Openid.CreateRequest(openIdUrl);
                        var fetch = new FetchRequest();
                        fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                        fetch.Attributes.AddOptional(WellKnownAttributes.Media.Images.FavIcon);
                        request.AddExtension(fetch);
                        return request.RedirectingResponse.AsActionResult();
                    }
                    catch (ProtocolException ex)
                    {
                        //_logger.Error("OpenID Exception...", ex);
                        return RedirectToAction("Login");
                    }
                }
                //_logger.Info("OpenID Error...invalid url. url='" + openIdUrl + "'");
                return RedirectToAction("Index", "Home");
            }

            // OpenID Provider sending assertion response
            switch (response.Status)
            {
                case AuthenticationStatus.Authenticated:
                    var fetch = response.GetExtension<FetchResponse>();
                    string firstName = "unknown";
                    string lastName = "unknown";
                    string email = "unknown";
                    string image = "unknow";
                    if (fetch != null)
                    {
                        firstName = fetch.GetAttributeValue(WellKnownAttributes.Name.First);
                        lastName = fetch.GetAttributeValue(WellKnownAttributes.Name.Last);
                        email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
                        image = fetch.GetAttributeValue(WellKnownAttributes.Media.Images.FavIcon);

                        WriteCookie(firstName, lastName, email, image);

                        if (!String.IsNullOrEmpty(Request["returnUrl"]))
                        {
                            Response.Redirect(Request["returnUrl"]);
                        }
                        else
                        {
                            return RedirectToAction("Index", "Home");
                        }
                    }
                    return RedirectToAction("Index", "Home");
                case AuthenticationStatus.Canceled:
                    //_logger.Info("OpenID: Cancelled at provider.");
                    return RedirectToAction("Login");
                case AuthenticationStatus.Failed:
                    //_logger.Error("OpenID Exception...", response.Exception);
                    return RedirectToAction("Login");
            }
            return RedirectToAction("Login");
        }

        public ActionResult Logout()
        {
            Response.Cookies.Clear();

            return RedirectToAction("Index", "Home");
        }

        private void WriteCookie(string firstName, string lastName, string email, string imgSrc)
        {
            string cookieValues = "{0}&{1}&{2}&{3}";

            cookieValues = string.Format(cookieValues, firstName, lastName, email, imgSrc);

            HttpCookie cookie = new HttpCookie("OpenIDUserInfo", cookieValues);

            Response.Cookies.Add(cookie);
        }

    }
}
